package main

import (
	"context"
	"fmt"
	"github.com/mongodb/mongo-go-driver/bson"
	"github.com/mongodb/mongo-go-driver/mongo"
	"github.com/mongodb/mongo-go-driver/mongo/options"
	"time"
)

type TimePoint struct {
	StartTime int64 `bson:"startTime"`
	EndTime   int64 `bson:"endTime"`
}

type LogRecord struct {
	JobName   string    `bson:"jobName"`
	Command   string    `bson:"command"`
	Err       string    `bson:"err"`
	Content   string    `bson:"content"`
	TimePoint TimePoint `bson:"timePoint"`
}

// jobName 过滤条件
type FindByJobName struct {
	JobName string `bson:"jonName"`
}

func main() {
	var (
		mongo_uri  string
		opts       *options.ClientOptions
		client     *mongo.Client
		err        error
		database   *mongo.Database
		collection *mongo.Collection
		//cond       *FindByJobName
		cursor   mongo.Cursor
		record   *LogRecord
		findopts *options.FindOptions
	)
	// 1. 建立连接
	mongo_uri = "mongodb://127.0.0.1:27017"
	opts = options.Client()
	opts.SetConnectTimeout(5 * time.Second)
	if client, err = mongo.Connect(context.TODO(), mongo_uri, opts); err != nil {
		fmt.Println(err)
		return
	}
	// 2. 选择数据库 my_db
	database = client.Database("cron")
	// 3. 选择表 my_collection
	collection = database.Collection("logs")

	// 4. 查询 按照jobName字段进行过滤，只要2条
	//cond = &FindByJobName{JobName: "job10"}
	findopts = options.Find()
	findopts.SetSkip(0)
	findopts.SetLimit(2)

	//if cursor, err = collection.Find(context.TO DO(), bson.D{{"jobName", "job10"}}, findopts); err != nil {
	//	fmt.Println(err)
	//	return
	//}
	if cursor, err = collection.Find(context.TODO(), bson.M{"jobName": "job10", "timePoint.startTime": bson.M{"$lt": time.Now().Unix()}}, findopts); err != nil {
		fmt.Println(err)
		return
	}

	defer cursor.Close(context.TODO())

	for cursor.Next(context.TODO()) {
		record = &LogRecord{}

		// 反序列化
		if err = cursor.Decode(record); err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(*record)
	}

}
